var express = require('express')
var router = express.Router()
const sqlQuery = require('../../module/sqlQuery')
const { resJsonObject, recordsStatusArr } = require('../../module/canshu')
const moment = require('moment')

// 获取挂号页面需要的数据
router.get('/guahao/pickdata', async function (req, res, next) {
  const clinicPickerData = await sqlQuery(
    'SELECT id,name,brief FROM doctors_category'
  )

  const doctorPickerData = await sqlQuery(
    'SELECT id,name,category_id,status FROM doctorslist'
  )

  res.json(
    resJsonObject({
      code: 0,
      msg: '获取成功',
      data: {
        clinicPickerData,
        doctorPickerData,
      },
    })
  )
})

router.get('/', async function (req, res, next) {
  const news_category_name = '默认'
  const options = {}

  try {
    const results = await sqlQuery(
      `SELECT newslist.id as id,
      title,
      author,
      pubtime,
      content,
      categoryid,
      status,
      news_category.name as category_name,
      brief
      FROM newslist LEFT JOIN news_category ON newslist.categoryid=news_category.id where status=1 and news_category.name = ?`,
      [news_category_name]
    )

    // console.log(results)

    options.newsList = results || []

    res.render('mobile/index', options)
  } catch (error) {
    console.log(error)
    res.render('mobile/index', options)
  }
})

router.get('/guahao', async function (req, res, next) {
  if (req.session.patient_id) {
    res.render('mobile/guahao', {
      patientInfo: {
        patient_name: req.session.patient_name,
      },
    })
  } else {
    res.render('info/info.ejs', {
      title: '用户信息',
      content: '未登录',
      hrefUrl: '/mobile/login',
      hrefTitle: '跳往登录页',
      info: '',
    })
  }
})

router.post('/guahao', async function (req, res, next) {
  try {
    console.log(req.body)
    const { clinic_id, doctor_id, dateTime } = req.body

    const registration_time = new Date().getTime()
    const visit_time = moment(dateTime).valueOf()
    // 默认状态未看病
    const status = 1

    const sqlStr = `insert into registration_record (patient_id,clinic_id,registration_time,visit_time,doctor_id,status) values (?,?,?,?,?,?)`
    await sqlQuery(sqlStr, [
      req.session.patient_id,
      clinic_id,
      registration_time,
      visit_time,
      doctor_id,
      status,
    ])
    // console.log(results)
    res.json(
      resJsonObject({
        code: 0,
        msg: '添加成功',
      })
    )
  } catch (error) {
    console.log(error)
    res.json(
      resJsonObject({
        code: 1,
        msg: '添加失败',
        data: {
          error,
        },
      })
    )
  }
})

router.get('/patientinfo', async function (req, res, next) {
  if (req.session.patient_id) {
    // 获取挂号列表数据
    const results = await sqlQuery(
      `SELECT re.id as id,
      patientslist.name as patient_name,
      doctors_category.name as clinic_name,
      re.registration_time as registration_time,
      re.visit_time as visit_time,
      doctorslist.name as doctor_name,
      re.status as record_status,
      re.content as record_content
      FROM registration_record as re
      LEFT JOIN patientslist
      ON re.patient_id=patientslist.id
      LEFT JOIN doctors_category
      ON re.clinic_id=doctors_category.id
      LEFT JOIN doctorslist
      ON re.doctor_id=doctorslist.id
      where patientslist.name like ?`,
      [req.session.patient_name]
    )

    results.forEach((item, index, arr) => {
      // 日期变换
      arr[index] = {
        ...item,
        registration_time_text: moment(parseInt(item.registration_time)).format(
          'YYYY-MM-DD hh:mm:ss'
        ),
        visit_time_text: moment(parseInt(item.visit_time)).format(
          'YYYY-MM-DD hh:mm:ss'
        ),
      }
    })

    results.forEach((item, index, arr) => {
      // // 挂号状态变换
      recordsStatusArr.forEach((status_item) => {
        if (status_item.id === item.record_status) {
          arr[index] = {
            ...item,
            record_status_text: status_item.value,
          }
          return
        }
      })
    })

    // console.log(results)

    res.render('mobile/patientInfo', { recordsList: results })
  } else {
    res.render('info/info.ejs', {
      title: '用户信息',
      content: '未登录',
      hrefUrl: '/mobile/login',
      hrefTitle: '跳往登录页',
      info: '',
    })
  }
})

router.get('/login', async function (req, res, next) {
  res.render('mobile/login')
})

router.post('/login', async function (req, res, next) {
  const { patient_phone, patient_password } = req.body
  const sqlStr = `select * from patientslist where phonenum=? and password=?`
  const results = await sqlQuery(sqlStr, [patient_phone, patient_password])
  if (results.length > 0) {
    req.session.patient_name = results[0].name
    req.session.patient_id = results[0].id
    res.render('info/info.ejs', {
      title: '用户信息',
      content: '登录成功',
      hrefUrl: '/mobile/guahao',
      hrefTitle: '跳往挂号页',
      hrefUrl2: '/mobile/patientinfo',
      hrefTitle2: '跳往个人页',
      hrefUrl3: '/mobile',
      hrefTitle3: '跳往主页',
      info: '',
    })
  } else {
    res.render('info/info.ejs', {
      title: '用户信息',
      content: '用户名或密码错误',
      hrefUrl: '/mobile/login',
      hrefTitle: '跳往登录页',
      info: '',
    })
  }
})

module.exports = router
